﻿using Hx.ADSyncPlatform.ActiveDirectory;
using Hx.ADSyncPlatform.ActiveDirectory.Model;
using Hx.ADSyncPlatform.Controllers.Base;
using Hx.ADSyncPlatform.Entity.Entities;
using Hx.ADSyncPlatform.Entity.Models;
using Hx.ADSyncPlatform.Infrastructure.Expression.Common;
using Hx.ADSyncPlatform.Infrastructure.Page;
using Hx.ADSyncPlatform.Service;
using Hx.ADSyncPlatform.WebApi.AutoMapper;
using Hx.ADSyncPlatform.WebApi.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Hx.ADSyncPlatform.Controllers
{
    /// <summary>
    /// AzureAD
    /// </summary>
    [Route("api/plat/user")]
    //[Authorize(policy: "privilege")]
    [ApiController]
    public class Plat_SysManagerController : BaseController
    {
        private Plat_SysManagerService plat_SysManagerService;
        private Plat_SysRoleService plat_SysRoleService;
        private ActiveDirectoryClient activeDirectoryClient;
        private Plat_DataPermissionService plat_DataPermissionService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="plat_SysManagerService"></param>
        /// <param name="plat_SysRoleService"></param>
        /// <param name="serviceProvider"></param>
        public Plat_SysManagerController(Plat_SysManagerService plat_SysManagerService,
            ActiveDirectoryClient activeDirectoryClient,
            Plat_DataPermissionService plat_DataPermissionService,
            Plat_SysRoleService plat_SysRoleService, IServiceProvider serviceProvider) : base(serviceProvider)

        {
            this.plat_SysManagerService = plat_SysManagerService;
            this.plat_SysRoleService = plat_SysRoleService;
            this.activeDirectoryClient = activeDirectoryClient;
            this.plat_DataPermissionService = plat_DataPermissionService;
        }
        ///// <summary>
        ///// 添加
        ///// </summary>
        ///// <param name="CreateOrUpdatePlatManagerRequest"></param>
        ///// <returns></returns>
        //[HttpPost("add")]
        //public async Task<Result<bool>> Add([FromBody] CreateOrUpdatePlatManagerRequest createOrUpdatePlatManagerRequest)
        //{

        //    bool isRepeat = await plat_SysManagerService.Count(n => n.UserName == createOrUpdatePlatManagerRequest.UserName) > 0;

        //    if (isRepeat) return await base.Fail<bool>($"用户名【{createOrUpdatePlatManagerRequest.UserName}】不允许重复!");

        //    var manager = mapper.Map<Plat_SysManager>(createOrUpdatePlatManagerRequest);

        //    plat_SysManagerService.AddPlatManagerAndRoles(manager);

        //    logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】添加了新的平台管理员【{createOrUpdatePlatManagerRequest.UserName}】 ");

        //    return await base.Success<bool>(true);

        //}

        /// <summary>
        /// SSO添加平台管理员
        /// </summary>
        /// <param name="CreateOrUpdatePlatManagerRequest"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<Result<bool>> Add([FromBody] CreateOrUpdatePlatManagerRequest createOrUpdatePlatManagerRequest)
        {
            createOrUpdatePlatManagerRequest.UserName = createOrUpdatePlatManagerRequest.UserName.Trim();
            bool isRepeat = await plat_SysManagerService.Count(n => n.UserName == createOrUpdatePlatManagerRequest.UserName) > 0;

            if (isRepeat) return await base.Fail<bool>($"员工【{createOrUpdatePlatManagerRequest.UserName}】已经是管理员，不允许重复添加!");

            Person person = activeDirectoryClient.Persons.Single(createOrUpdatePlatManagerRequest.UserName);

            if (person == null) return await base.Fail<bool>($"员工【{createOrUpdatePlatManagerRequest.UserName}】已不存在，请刷新后重试！");


            Plat_SysManager manager = new Plat_SysManager()
            {
                ObjectGuid = person.CObjectGUID,
                UserName = createOrUpdatePlatManagerRequest.UserName,
                IsEnable = true,
                RoleIds = createOrUpdatePlatManagerRequest.RoleIds
            };

            plat_SysManagerService.AddPlatManagerAndRoles(manager);

            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】添加了新的平台管理员【{createOrUpdatePlatManagerRequest.UserName}】 ");

            return await base.Success<bool>(true);

        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="id"></param>
        /// <param name="CreateOrUpdatePlatManagerRequest"></param>
        /// <returns></returns>
        [HttpPost("edit/{id}")]
        public async Task<Result<bool>> Edit([FromRoute] Guid id, [FromBody] CreateOrUpdatePlatManagerRequest createOrUpdatePlatManagerRequest)
        {
            if (id == Guid.Empty) return await base.Fail<bool>($"未找到该用户!");

            bool isRepeat = await plat_SysManagerService.Count(n => n.UserId != createOrUpdatePlatManagerRequest.UserId && n.UserName == createOrUpdatePlatManagerRequest.UserName) > 0;

            if (isRepeat) return await base.Fail<bool>($"用户名【{createOrUpdatePlatManagerRequest.UserName}】不允许重复!");

            var manager = mapper.Map<Plat_SysManager>(createOrUpdatePlatManagerRequest);

            plat_SysManagerService.UpdatePlatManagerAndRoles(manager);

            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】修改了平台管理员信息,管理员id为【{id}】 ");

            return await base.Success<bool>(true);

        }



        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost("resetPassword")]
        public async Task<Result<bool>> ResetPassword([FromQuery] int userId)
        {

            bool res = plat_SysManagerService.ResetPassword(userId);

            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】重置了管理员的密码,管理员id为【{userId}】 ");

            return await base.Success<bool>(res);
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="changePasswordRequest"></param>
        /// <returns></returns>
        [HttpPost("changePassword")]
        public async Task<Result<string>> ChangePassword([FromQuery] int userId, [FromBody] ChangePasswordRequest changePasswordRequest)
        {

            string defaultPassword = plat_SysManagerService.ChangePassword(userId, changePasswordRequest.OldPassword,
                changePasswordRequest.NewPassword,
                changePasswordRequest.ConfirmPassword);
            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】修改了管理员的密码,管理员id为【{userId}】 ");
            return await base.Success<string>(defaultPassword);

        }


        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<Result<PageResult<Plat_SysManagerViewModel>>> GetList([FromQuery] Pagination pagination,
            [FromQuery] Dictionary<string, string> param)
        {

            PageResult<Plat_SysManager> pageList = await plat_SysManagerService.GetManagerList(pagination, param);

            PageResult<Plat_SysManagerViewModel> pageResult =
                mapper.MapToPage<Plat_SysManager, Plat_SysManagerViewModel>(pageList);

            return await base.Success<PageResult<Plat_SysManagerViewModel>>(pageResult);

        }


        /// <summary>
        /// 获取单个用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("get/{id}")]
        public async Task<Result<Plat_SysManagerViewModel>> GetUser([FromRoute] int id)
        {
            var user = await plat_SysManagerService.QueryById(id);
            if (user == null)
            {
                return await base.Fail<Plat_SysManagerViewModel>("用户已不存在");
            }
            Plat_SysManagerViewModel plat_SysManagerViewModel = mapper.Map<Plat_SysManagerViewModel>(user);
            var roles = plat_SysRoleService.GetRolesByUserId(user.UserId);
            plat_SysManagerViewModel.RoleIds = roles.Select(n => n.RoleID).ToList();

            return await base.Success<Plat_SysManagerViewModel>(plat_SysManagerViewModel);
        }


        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("delete/{id}")]
        public async Task<Result<bool>> Delete([FromRoute] Guid id)
        {
            bool deleted = await plat_SysManagerService.DeleteById(id);
            await plat_DataPermissionService.DeleteDataPermissionsByManagerGuid(id);
            logHelper.WriteToDb(BehaviorType.Operation, $"用户【{platManager.Name}】删除了管理员账户,管理员id为【{id}】 ");
            return await base.Success<bool>(true);
        }


        [HttpPost("{id}/roles")]
        public async Task<Result<bool>> AssignRoles([FromRoute] Guid id, [FromBody] List<Guid> roleIds)
        {
            Plat_SysManager plat_SysManager = await plat_SysManagerService.QueryById(id);
            plat_SysManager.RoleIds = roleIds;
            bool result = plat_SysManagerService.UpdatePlatManagerAndRoles(plat_SysManager);
            return await base.Success<bool>(result);
        }


    }
}
